package com.community.sqlapp.dpsToXmind;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 文档解析类
 */
@Component
public class DocParser {
    public String parseDocFile(String filePath) throws IOException {
        if (filePath.endsWith(".docx")) {
            // 解析docx
            FileInputStream fis = new FileInputStream(new File(filePath));
            XWPFDocument document = new XWPFDocument(fis);
            StringBuilder content = new StringBuilder();
            for (XWPFParagraph para : document.getParagraphs()) {
                content.append(para.getText()).append("\n");
            }
            fis.close();
            return content.toString();
        } else if (filePath.endsWith(".doc")) {
            // 解析doc
            FileInputStream fis = new FileInputStream(new File(filePath));
            HWPFDocument document = new HWPFDocument(fis);
            Range documentRange = document.getRange();
            StringBuilder content = new StringBuilder();
            int paraCount = documentRange.numParagraphs();
            for (int i = 0; i < paraCount; i++) {
                Paragraph paragraph = documentRange.getParagraph(i);
                content.append(paragraph.text()).append("\n");
            }
            fis.close();
            return content.toString();
        } else {
            throw new IllegalArgumentException("只支持doc和docx文件");
        }
    }
}